package vip.xiaomoli.nurse.component;

import cn.hutool.core.util.ReflectUtil;
import vip.xiaomoli.nurse.model.Api;
import vip.xiaomoli.nurse.model.FieldWrapper;
import vip.xiaomoli.nurse.util.ApplicationContextHelper;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class InjectProcessor {

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            20, Integer.MAX_VALUE,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<>()
    );

    public static void process() {
        Map<Api, Map<Object, List<FieldWrapper>>> apiMap = InjectContainer.get();
        apiMap.forEach((api, paramValueMap) -> executor.execute(() -> {
            Object bean = ApplicationContextHelper.getSpringOrDubboBean(api.getApiClass());
            Collection result = ReflectUtil.invoke(bean, api.getMethodName(), paramValueMap.keySet());
            //noinspection unchecked
            Map<Object, Object> resultMap = (Map<Object, Object>) result;
            paramValueMap.forEach((paramValue, fieldWrapperList) -> fieldWrapperList.forEach(fieldWrapper -> {
                fieldWrapper.setValue(resultMap.get(paramValue));
            }));
        }));
    }

}
